<template>
  <div class="wrapper">
    <!-- 卡片组件 -->
    <card v-if="!homePage" :_Size="16" :_Tabs="changeWay" :_Title="$t('base.my.order')" @_Change="change"></card>
    <card v-else :_More="$t('order.all')" :_Size="16" :_Tabs="changeWay" :_Title="$t('base.my.order')"
          _Src="/home/MyOrder"
          @_Change="change"></card>
    <!-- 搜索 筛選 -->
    <div v-if="!homePage" class="mb_24 box">
      <div class="global_float_right">
        <Input
          v-model="params.keywords"
          class="width_300"
          enter-button
          :placeholder="$t('my.order_search')"
          search
          @on-search="getList"
        />
      </div>
    </div>
    <!-- 訂單列表 -->
    <empty v-if="orderList.length === 0"/>
    <div v-else class="order-content">
      <div
        v-for="(order, onderIndex) in orderList"
        :key="onderIndex"
        class="order-list"
      >
        <div class="order-header">
          <div>
            <div>{{ filterOrderStatus(order.orderStatus) }}</div>
            <div>
              {{ $t('order.no') }}：{{ order.sn }} &nbsp; &nbsp; &nbsp;{{ order.createTime }}
            </div>
          </div>
          <div>
            <Button v-if="order.orderStatus === 'COMPLETED'" class="del-btn mr_10 fontsize_16"
                    icon="ios-trash-outline" size="small" style="margin-top:-5px;" type="text"
                    @click="delOrder(order.sn)"></Button>
            <span>{{ order.flowPrice | unitPrice("HK$") }}</span>
          </div>
        </div>
        <div class="order-body">
          <div class="goods-list">
            <div
              v-for="(goods, goodsIndex) in order.orderItems"
              :key="goodsIndex"
            >
              <img
                :src="goods.image"
                alt=""
                class="hover-color"
                @click="goodsDetail(goods.skuId, goods.goodsId)"
              />
              <div>
                <div class="hover-color" @click="goodsDetail(goods.skuId, goods.goodsId)">{{ goods.name }}</div>
                <div class="mt_10">
                  <span class="global_color"
                  >{{ goods.goodsPrice | unitPrice("HK$") }} </span
                  >x {{ goods.num }}
                </div>
                <Button v-if="goods.commentStatus == 'UNFINISHED'" class="fontsize_12" size="small"
                        style="position:relative;top:-22px;left:100px;margin-right:10px" type="success"
                        @click="comment(order.sn, goodsIndex)">{{ $t('base.evaluate') }}
                </Button>
                <Button v-if="goods.complainStatus == 'NO_APPLY'" class="fontsize_12" size="small"
                        style="position:relative;top:-22px;left:100px" type="warning"
                        @click="complain(order.sn, goodsIndex)">{{ $t('base.complaint') }}
                </Button>
              </div>
            </div>
          </div>
          <div>
            <span @click="shopPage(order.storeId)">{{ order.storeName }}</span>
          </div>
          <div>
            <!-- 訂單基础操作 -->
            <Button size="small" type="info" @click="orderDetail(order.sn)">{{ $t('order.details') }}</Button>
            <Button v-if="order.allowOperationVO.cancel" size="small" type="error" @click="handleCancelOrder(order.sn)">
              {{ $t('order.cancellation') }}
            </Button>
            <Button v-if="order.allowOperationVO.pay" size="small" type="success" @click="goPay(order.sn)">
              {{ $t('base.go.pay') }}
            </Button>
            <Button @click="delOrder(order.sn)" type="error" v-if="!order.allowOperationVO.cancel" size="small">刪除訂單</Button>
            <Button v-if="order.allowOperationVO.rog" size="small" type="warning" @click="received(order.sn)">
              {{ $t('base.confirmReceipt') }}
            </Button>
            <!-- 售後 -->
            <Button
              v-if="order.groupAfterSaleStatus && (order.groupAfterSaleStatus==='NOT_APPLIED'|| order.groupAfterSaleStatus==='PART_AFTER_SALE' )"
              size="small" @click="applyAfterSale(order.orderItems)">{{ $t('apply.afterSales') }}
            </Button>
          </div>
        </div>
      </div>
      <Spin v-if="spinShow" fix size="large"></Spin>
    </div>
    <!-- 分頁 -->
    <div v-if="!homePage" class="page-size">
      <Page :page-size="params.pageSize" :total="total"
            show-sizer
            show-total
            @on-change="changePageNum"
            @on-page-size-change="changePageSize">
      </Page>
    </div>
    <!-- 選擇售後商品 -->
    <Modal v-model="afterSaleModal" title="請選擇申請售後的商品">
      <div>
        <Table
          :columns="afterSaleColumns"
          :data="afterSaleArr"
          border
          @on-row-click="afterSaleSelect"
        >
        </Table>
      </div>
      <div slot="footer"></div>
    </Modal>
    <Modal v-model="cancelAvail" title="請選擇取消訂單原因" @on-ok="sureCancel" @on-cancel="cancelAvail = false">
      <RadioGroup v-model="cancelParams.reason" button-style="solid" type="button" vertical>
        <Radio v-for="item in cancelReason" :key="item.id" :label="item.reason">
          {{ item.reason }}
        </Radio>
      </RadioGroup>
    </Modal>
  </div>
</template>

<script>
import {cancelOrder, delOrder, getOrderList, sureReceived} from '@/api/order';
import {afterSaleReason} from '@/api/member';
import {orderStatusList} from '../enumeration.js'
import i18n from "@/lang";

export default {
  i18n,
  name: 'MyOrder',
  props: {
    homePage: { // 判断是否个人中心首頁展示内容
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      orderList: [], // 訂單列表
      params: { // 請求參數
        pageNumber: 1,
        pageSize: 10,
        // orderStatus: 'ALL',
        keywords: '',
        tag: 'ALL'
      },
      cancelParams: { // 取消售後參數
        orderSn: '',
        reason: ''
      },
      // 狀態數组
      orderStatusList,
      total: 0, // 數据总數
      spinShow: false, // 加载狀態
      afterSaleModal: false, // 選擇售後商品模态框
      afterSaleColumns: [ // 售後商品表頭
        {title: '商品名稱', key: 'name'},
        {title: '價格', key: 'goodsPrice'}
      ],
      afterSaleArr: [], // 售後商品列表
      cancelAvail: false, // 取消訂單modal控制
      cancelReason: [] // 取消訂單原因
    };
  },
  mounted() {
    if (this.homePage) this.params.pageSize = 5;
    this.getList();
  },
  computed: {
    changeWay() {
      return [i18n.t('order.all'), i18n.t('base.toPayment'), i18n.t('base.toSend'), i18n.t('base.completed')];
    }
  },
  methods: {
    goodsDetail(skuId, goodsId) {
      // 跳轉商品詳情
      let routeUrl = this.$router.resolve({
        path: '/goodsDetail',
        query: {skuId, goodsId}
      });
      window.open(routeUrl.href, '_blank');
    },
    // 切换訂單狀態
    change(index) {
      switch (index) {
        case 0:
          this.params.tag = 'ALL'
          break;
        case 1:
          this.params.tag = 'WAIT_PAY'
          break;
        case 2:
          this.params.tag = 'WAIT_ROG'
          break;
        case 3:
          this.params.tag = 'COMPLETE'
          break;
      }
      this.getList()
    },
    // 跳轉店铺首頁
    shopPage(id) {
      let routeUrl = this.$router.resolve({
        path: '/Merchant',
        query: {id: id}
      });
      window.open(routeUrl.href, '_blank');
    },
    orderDetail(sn) {
      // 跳轉訂單詳情
      this.$router.push({name: 'OrderDetail', query: {sn}});
    },
    received(sn) { // 確認收貨
      sureReceived(sn).then(res => {
        if (res.success) {
          this.$Message.success('確認收貨成功')
          this.getList()
        }
      })
    },
    goPay(sn) { // 去支付
      this.$router.push({path: '/payment', query: {orderType: 'ORDER', sn}});
    },
    applyAfterSale(goodsItem) { // 申請售後
      let arr = []
      goodsItem.forEach(e => {
        if (e.afterSaleStatus === 'NOT_APPLIED' || e.afterSaleStatus === 'PART_AFTER_SALE') {
          arr.push(e)
        }
      });
      if (arr.length === 1) {
        this.$router.push({name: 'ApplyAfterSale', query: {sn: arr[0].sn}})
      } else {
        this.afterSaleArr = arr;
        this.afterSaleModal = true
      }
    },
    // 申請售後
    afterSaleSelect(item) {
      this.$router.push({name: 'ApplyAfterSale', query: {sn: item.sn}})
    },
    comment(sn, goodsIndex) { // 評價
      this.$router.push({path: '/home/addEval', query: {sn, index: goodsIndex}})
    },
    complain(sn, goodsIndex) { // 投訴
      this.$router.push({name: 'Complain', query: {sn, index: goodsIndex}})
    },
    delOrder(sn) { // 删除訂單
      this.$Modal.confirm({
        title: '删除訂單',
        content: '<p>確認删除当前訂單吗？</p>',
        onOk: () => {
          delOrder(sn).then(res => {
            if (res.success) {
              this.$Message.success('删除成功');
              this.getList()
            }
          })
        },
        onCancel: () => {
        }
      });
    },
    getList() { // 获取訂單列表
      this.spinShow = true;
      let params = JSON.parse(JSON.stringify(this.params))
      if (params.orderStatus === 'ALL') {
        delete params.orderStatus
      }
      getOrderList(params).then(res => {
        this.spinShow = false
        if (res.success) {
          this.orderList = res.result.records;
          this.total = res.result.total;
        }
      });
    },
    changePageNum(val) { // 修改頁碼
      this.params.pageNumber = val;
      this.getList()
    },
    changePageSize(val) { // 修改頁數
      this.params.pageNumber = 1;
      this.params.pageSize = val;
      this.getList()
    },
    handleCancelOrder(sn) {
      // 取消訂單
      this.cancelParams.orderSn = sn;
      afterSaleReason('CANCEL').then(res => {
        if (res.success) {
          this.cancelReason = res.result;
          this.cancelAvail = true
          this.cancelParams.reason = this.cancelReason[0].reason
        }
      })
    },
    sureCancel() { // 确定取消
      cancelOrder(this.cancelParams).then(res => {
        if (res.success) {
          this.$Message.success('取消訂單成功')
          this.getList()
          this.cancelAvail = false
        }
      })
    },
    filterOrderStatus(status) { // 获取訂單狀態中文
      const ob = this.orderStatusList.filter(e => {
        return e.status === status
      });
      return ob && ob[0] ? ob[0].name : status
    }
  }
};
</script>

<style lang="scss" scoped>
.wrapper {
  margin-bottom: 40px;
}

.box {
  overflow: hidden;
}

.page-size {
  margin: 15px 0px;
  text-align: right;
}

/** 訂單列表 */
.order-list {
  border: 1px solid #ddd;
  border-radius: 3px;
  margin-bottom: 10px;

  &:hover {
    .del-btn {
      visibility: visible;
    }
  }

  .del-btn {
    visibility: hidden;
  }

  .order-header {
    display: flex;
    align-items: center;
    padding: 10px;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;

    > div:nth-child(1) > div:nth-child(2) {
      font-size: 12px;
      color: #999;
      margin-top: 3px;
    }
  }

  .order-body {
    display: flex;
    justify-content: space-between;
    color: #999;
    padding: 10px;

    .goods-list > div {
      width: 500px;
      display: flex;
      margin-bottom: 10px;

      img {
        width: 60px;
        height: 60px;
        margin-right: 10px;
      }

      > div {
        flex: 1;
      }
    }

    > div:nth-child(2) {
      width: 150px;
      text-align: center;

      span {
        color: #438cde;
        cursor: pointer;

        &:hover {
          color: $theme_color;
        }
      }

      .ivu-icon {
        color: #ff8f23;
        cursor: pointer;

        &:hover {
          color: $theme_color;
        }
      }
    }

    > div:nth-child(3) {
      width: 100px;

      .ivu-btn {
        margin-bottom: 10px;
      }
    }
  }
}
</style>
